package com.yiwei.zhh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.yiwei.zhh.R;
import com.yiwei.zhh.activity.Application;
import com.yiwei.zhh.activity.BankIdentityActivity;
import com.yiwei.zhh.activity.MainActivityNew;
import com.yiwei.zhh.activity.StepBankIdentityActivity;
import com.yiwei.zhh.activity.V3AddressIdentityActivity;
import com.yiwei.zhh.activity.V3CarIdentityActivity;
import com.yiwei.zhh.activity.V3EmailIdentityActivity;
import com.yiwei.zhh.activity.V3FaceIdentityOneActivity;
import com.yiwei.zhh.activity.V3HouseIdentityActivity;
import com.yiwei.zhh.activity.V3IdcardIdentityActivity;
import com.yiwei.zhh.activity.V3IdentitySuccessInfoActivity;
import com.yiwei.zhh.activity.V3IncomeIdentityActivity;
import com.yiwei.zhh.activity.V3TaobaoIdentityActivity;
import com.yiwei.zhh.activity.V3WorkIdentityActivity;
import com.yiwei.zhh.activity.V3XueXinIdentityActivity;
import com.yiwei.zhh.activity.V3YunYingIdentityActivity;
import com.yiwei.zhh.adapter.AllIdentityHomeAdapter;
import com.yiwei.zhh.adapter.AllIdentityOneAdapter;
import com.yiwei.zhh.adapter.IdentityTypsInterface;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.LiMuKeyBean;
import com.yiwei.zhh.api.bean.LiMuSignBean;
import com.yiwei.zhh.api.bean.LiMuTokenBean;
import com.yiwei.zhh.api.bean.ZhiMaCertBean;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.constant.UserGlobal;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.PreferenceUtils;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.Dialog;
import com.yiwei.zhh.view.V19FrameLayout;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.bean.MessageEvent;
import kangcheng.com.lmzx_android_sdk_v10.bean.SignEvent;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSDK;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.DataCallBack;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.ObservableManager;

/**
 * Created by xsooy-pc on 18-9-3.
 */

public class AllIdentityFragment extends BaseFragment implements IdentityTypsInterface {


    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list_one)
    RecyclerView listOne;
    @BindView(R.id.btn_identity)
    SuperButton btnIdentity;
    @BindView(R.id.list_two)
    RecyclerView listTwo;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.btn_back)
    ImageView btnBack;

    private Unbinder unbinder;
    //    public final static String SUCCESS = "0";
//    public final static String LOGING_SUCCESS = "2";
//    private boolean initSuccess = false;
//    private String bizType;
    private AllIdentityHomeAdapter allIdentityOneAdapter;
    private AllIdentityHomeAdapter allIdentityTwoAdapter;
//    private boolean isFail = false;


    @Override
    protected int setLayoutId() {
        return R.layout.fragment_all_identity;
    }

    @Override
    protected void initView() {
        txtTitle.setText("全部认证");

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getMyCertification();
            }
        });
        allIdentityOneAdapter = new AllIdentityHomeAdapter(getContext());
        allIdentityOneAdapter.setOnChooseListener(this);
        listOne.setLayoutManager(new GridLayoutManager(getContext(), 3));
        listOne.setAdapter(allIdentityOneAdapter);

        allIdentityTwoAdapter = new AllIdentityHomeAdapter(getContext());
        allIdentityTwoAdapter.setOnChooseListener(this);
        listTwo.setLayoutManager(new GridLayoutManager(getContext(), 3));
        listTwo.setAdapter(allIdentityTwoAdapter);
//        getKey(UserGlobal.getDealId());
    }

//    private void init() {
//       
//    }

    private void getLmSdkKey() {
        ((MainActivityNew) getActivity()).getKey(UserGlobal.getDealId());
    }


    @Override
    public void onResume() {
        super.onResume();
        if (refresh != null && refresh.isRefreshing()) {
            refresh.setRefreshing(false);
        }
        if (UserGlobal.checkLogin()) {
            if (!((MainActivityNew) getActivity()).initSuccess) {
                getLmSdkKey();
            }
            getMyCertification();
        }
    }

    public void getMyCertification() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getMyCertification().compose(RxLifeUtil.NocheckOn(getContext())).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        allIdentityOneAdapter.update(result.data.basic);
                        allIdentityTwoAdapter.update(result.data.optional);
                    }
                });
    }


    public void getOneKeyIdentity() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.makeText(getContext(), "网络连接失败").show();
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getCertificationBasics().compose(RxLifeUtil.checkOn(getContext())).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(item -> {
                    if (item.data != null && item.data.size() != 0) {

                        if (item.data.get(0).iscert.equals("0")) {
                            Intent intent = new Intent();
                            switch (item.data.get(0).remark) {
                                case Const.IdentityType.yunyin:
                                    intent.setClass(getContext(), V3YunYingIdentityActivity.class);
                                    break;
                                case Const.IdentityType.contacts:
                                    intent.setClass(getContext(), V3AddressIdentityActivity.class);
                                    break;
                                case Const.IdentityType.realname:
                                    intent.setClass(getContext(), V3IdcardIdentityActivity.class);
                                    break;
                                case Const.IdentityType.taobao:
                                    intent.setClass(getContext(), V3TaobaoIdentityActivity.class);
                                    break;
                                case Const.IdentityType.face_detect:
                                    intent.setClass(getContext(), V3FaceIdentityOneActivity.class);
                                    break;
                                case Const.IdentityType.xuexin:
                                    intent.setClass(getContext(), V3XueXinIdentityActivity.class);
                                    break;
                                case Const.IdentityType.bankcard:
                                    intent.setClass(getContext(), StepBankIdentityActivity.class);
                                    break;
                            }
                            intent.putExtra(Const.KEY.ONE_KEY, item.data);
                            startActivity(intent);
                            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);


                        }
                    }else {
                        ToastUtil.makeText(getContext(),"已全部认证完成");
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unbinder.unbind();
        unbinder = null;
    }

    @OnClick({R.id.btn_identity})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_identity:
                getOneKeyIdentity();
                break;
        }
    }

    @Override
    public void onClick(String iscert, String remark) {
        if (!UserGlobal.getIsIdcardPass()) {
            Dialog.gotoShiMing(getContext(), new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Util.startActivity(getActivity(), V3IdcardIdentityActivity.class);
                }

                @Override
                public void cancel() {

                }
            }).show();

            return;
        }
        ((MainActivityNew) getActivity()).bizType = remark;
        if (iscert.equals("1")) {
            Intent intent = new Intent(getContext(), V3IdentitySuccessInfoActivity.class);
            intent.putExtra("remark", remark);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
            return;
        }
        switch (remark) {
            case Const.IdentityType.yunyin:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                if (TextUtils.isEmpty(PreferenceUtils.getString(getContext(), "mobile", "")) || Const.IS_DEBUG) {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(getContext(), "", true);
                } else {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(getContext(), PreferenceUtils.getString(getContext(), "mobile", ""), false);
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionMobileCarrie, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.car:
                Util.startActivity(getContext(), V3CarIdentityActivity.class);
                break;
            case Const.IdentityType.contacts:
                Util.startActivity(getContext(), V3AddressIdentityActivity.class);
                break;

            case Const.IdentityType.email:
                Util.startActivity(getContext(), V3EmailIdentityActivity.class);
                break;

            case Const.IdentityType.face_detect:
                Intent intentFace = new Intent(getContext(), V3FaceIdentityOneActivity.class);
                intentFace.putExtra("isFromLoan", false);
                startActivity(intentFace);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;

            case Const.IdentityType.house:
                Util.startActivity(getContext(), V3HouseIdentityActivity.class);
                break;

            case Const.IdentityType.housefund:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionHousingFund, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.income:
                Util.startActivity(getContext(), V3IncomeIdentityActivity.class);
                break;

            case Const.IdentityType.jd:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionJD, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.linkedin:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionLinkedIn, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.realname:
                Util.startActivity(getContext(), V3IdcardIdentityActivity.class);
                break;

            case Const.IdentityType.socialsecurity:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionSocialSecurity, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.taobao:
                if (!((MainActivityNew) getActivity()).initSuccess) {
                    getLmSdkKey();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionTaoBao, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.work:
                Util.startActivity(getContext(), V3WorkIdentityActivity.class);
                break;
            case Const.IdentityType.xuexin:
                Util.startActivity(getContext(), V3XueXinIdentityActivity.class);
                break;
            case Const.IdentityType.bankcard:
                Util.startActivity(getContext(), BankIdentityActivity.class);
                break;
            case Const.IdentityType.zmscore:
                ((MainActivityNew) getActivity()).getZhiMaCertInfo();
                break;

        }
    }

//    @Override
//    public void signData(SignEvent signEvent) {
//        String sign = signEvent.getSignStr();//r3qUEj6PhkTz8odjHC0OYTXbtlSxqWyQ  //1.收到sdk传来的字符串
//        getSign(sign);
//    }
//
//    @Override
//    public void messageData(MessageEvent event) {
//        MessageEvent test = (MessageEvent) event;
////            Log.i("dasdadsadsadsasa", "code" + test.getCode() + ",message" + test.getMessage() + ",token" + test.getToken() + ",function" + test.getFunction() + ",hasmap" + test.getHashMap().toString());
//
//        if (SUCCESS.equals(((MessageEvent) event).getCode())) {
//            //具体哪个业务,参看文档的相关业务类型做处理
//            int function = ((MessageEvent) event).getFunction();
//            //服务密码
//            if (function == Fuction.LMZXSDKFunctionMobileCarrie) {
//                //...
//
//            }
//            //登录成功处理
//        } else if (LOGING_SUCCESS.equals(((MessageEvent) event).getCode())) {
//            //可以获取token值,记录提交请求,或者忽略掉
//            isFail = false;
//            uploadToken("", ((MessageEvent) event).getToken(), bizType);
//            //查询失败
//        } else {
//            isFail = true;
//            uploadToken("", ((MessageEvent) event).getToken(), bizType);
//            //失败处理,可忽略
////            Log.i("dadasdda", "失败code：" + ((MessageEvent) event).getCode() + "\ntoken=" + ((MessageEvent) event).getToken());
////            Intent intent = new Intent(getContext(), MyIdentityActivity.class);
////            startActivity(intent);
//        }
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
